import React, { useEffect, useRef, useState } from 'react';
import { Card, Col, Row, Avatar, List, Drawer } from 'antd';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import axios from 'axios';
import * as echarts from 'echarts'
import _ from 'lodash'
const { Meta } = Card;
export default function Home() {
    const [viewList, setviewList] = useState([])
    const [starList, setstarList] = useState([])
    const [allList, setallList] = useState([])
    const [open, setOpen] = useState(false);
    const barRef = useRef()
    const parRef = useRef()
    const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem('token'))
    useEffect(() => {
        axios.get('/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6').then(res => {
            setviewList(res.data)
        })
    }, [])
    useEffect(() => {
        axios.get('/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6').then(res => {
            setstarList(res.data)
        })
    }, [])

    useEffect(() => {
        axios.get('/news?publishState=2&_expand=category').then(res => {
            randerBarView(_.groupBy(res.data, (item) => item.category.title))
            setallList(res.data)
        })
        return () => { //组件销毁时触发
            window.onresize = null
        }
    }, [])

    const randerBarView = (obj) => {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(barRef.current);

        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '新闻分类图示'
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(obj),
                axisLabel: {
                    rotate: '45',
                    interval: 0
                }
            },
            yAxis: {
                minInterval: 1
            },
            series: [
                {
                    name: '销量',
                    type: 'bar',
                    data: Object.values(obj).map(i => i.length)
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);

        window.onresize = () => {
            myChart.resize()
        }
    }

    const renderParview = () => {
        let currList = allList.filter((item) => item.author === username)

        let groupList = _.groupBy(currList, (item) => item.category.title)
        var myParChart = echarts.init(parRef.current);
        let list = []
        for (let i in groupList) {
            list.push({
                name: i,
                value: groupList[i].length
            })
        }
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: `当前用户${username}的新闻分类图`,
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '发布数量',
                    type: 'pie',
                    radius: '50%',
                    data: list,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        // 使用刚指定的配置项和数据显示图表。
        option && myParChart.setOption(option);
    }
    const showDrawer = () => {
        setOpen(true);
        setTimeout(() => {
            renderParview()
        }, 0)
    };

    const onClose = () => {
        setOpen(false);
    };
    return (
        <div>
            <div className="site-card-wrapper">
                <Row gutter={16}>
                    <Col span={8}>
                        <Card title="用户最常浏览" bordered={false}>
                            <List
                                size='small'
                                dataSource={viewList}
                                renderItem={(item) => <List.Item>
                                    <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                                </List.Item>}
                            >
                            </List>
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card title="用户点赞最多" bordered={false}>
                            <List
                                size='small'
                                dataSource={starList}
                                renderItem={(item) => <List.Item>
                                    <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                                </List.Item>}
                            >
                            </List>

                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            style={{ width: 300 }}
                            cover={
                                <img
                                    alt="example"
                                    src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                                />
                            }
                            actions={[
                                <SettingOutlined key="setting" onClick={showDrawer} />,
                                <EditOutlined key="edit" />,
                                <EllipsisOutlined key="ellipsis" />,
                            ]}
                        >
                            <Meta
                                avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                                title={username}
                                description={
                                    <div>
                                        <b>{region || '全球'}</b>
                                        <span style={{ paddingLeft: '10px' }}>{roleName}</span>
                                    </div>
                                }
                            />
                        </Card>
                    </Col>
                </Row>
                <Drawer width='500px' title="Basic Drawer" placement="right" onClose={onClose} open={open}>
                    <div ref={parRef} style={{ height: '400px' }}></div>
                </Drawer>
                <div ref={barRef} style={{ height: '400px' }}></div>

            </div>
        </div>
    )
}
